﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class NotificationManager : MonoBehaviour 
{
	//-----------------------------------------------
	//-------singleton
	void Awake()
	{
		CheckSingletonInstance();
	}
	
	void CheckSingletonInstance()
	{
		// check duplicate instance
		if (instance != null && instance.GetInstanceID() != GetInstanceID() )
		{
			DestroyImmediate(gameObject);//delete duplicate
		}
		else
		{
			instance = this;
			//DontDestroyOnLoad(gameObject);// optiocal
		}
	}	
		
	private static NotificationManager instance = null;
	public static NotificationManager Instance
	{
		get
		{
			if (instance == null) instance = new GameObject("NotificationManager").AddComponent<NotificationManager>();
			return instance;
		}
	}



	//------------------------------------------------
	//Internal reference to all listeners for notifications
	private Dictionary<GameEnum.EventType, List<Component>> m_listeners = new Dictionary<GameEnum.EventType, List<Component>>();
	
	//Methods
	//------------------------------------------------
	//Function to add a listener for an notification to the listeners list
	public void AddListener(Component sender, GameEnum.EventType notificationType)
	{
		//Add listener to dictionary
		if(!m_listeners.ContainsKey(notificationType))
			m_listeners.Add (notificationType, new List<Component>());
		
		//Add object to listener list for this notification
		m_listeners[notificationType].Add(sender);
	}
	//------------------------------------------------
	//Function to remove a listener for a notification
	public void RemoveListener(Component sender, GameEnum.EventType notificationType)
	{
		//If no key in dictionary exists, then exit
		if ( !m_listeners.ContainsKey(notificationType))
		    return;
		//Cycle through listeners and identify component, and then remove
		List<Component> listeners = m_listeners[notificationType];
		for (int i = listeners.Count - 1; i >= 0; i--)
		{
			if (listeners[i].GetInstanceID() == sender.GetInstanceID())
				listeners.RemoveAt(i);
		}
	}
	//------------------------------------------------
	//Function to post a notification to a listener
	public void PostNotification(Component sender, GameEnum.EventType notificationType)
	{
		//If no key in dictionary exists, then exit
		if(!m_listeners.ContainsKey(notificationType))
			return;
		
		//Else post notification to all matching listeners
		IListener scriptPointer;
		foreach(Component listener in m_listeners[notificationType])
		{
			//Listener.SendMessage(notificationType, Sender, SendMessageOptions.DontRequireReceiver);
			//scriptPointer = listener.GetComponent<IListener>();
			scriptPointer = listener as IListener;
			if (scriptPointer != null) 	scriptPointer.OnNotificationReceived(sender);
		}
	}

}
